<?php

namespace api\admin;

use DOMDocument;
use utils\base64_to_file;
use utils\oss;
use utils\zip;

//自定义按钮类（富文本类）
class richtext

{
    //添加
    public function add($data){
        $name=$data['name'];
        $content=$data['content'];
        $time=time();


        //以下是富文本src里面的base64码转化成oss文件对象地址
        ini_set('pcre.backtrack_limit', 999999999);//临时解除匹配长度限制
        preg_match_all('/\"(data:image\/[a-zA-Z]+;base64,.*?)\"/', $content, $img);
        $img=$img[1];

        for($i=0;$i<count($img);$i++){
            $file=base64_to_file::get_image($img[$i]);
            $res=oss::upload("admin/mini/".$file["name"],$file["path"]);
            $url=$res["info"]["url"];

            $content=str_replace($img[$i],$url,$content);

        }
        //以上是富文本src里面的base64码转化成oss文件对象地址
        $content=str_replace("<img",'<img style="width:100%;height:auto"',$content);

        $img=$data['img'];
        $date=date('Y-m-d');
        $url='';
        for($i=0;$i<count($img);$i++){
            $file=base64_to_file::get("",$img[$i]["file_name"],$img[$i]["file"]);
            $res=oss::upload("richtext/$date/".$file["name"],$file["path"]);
            $url=$res["info"]["url"];
        }

        $con=con();
        $res=mysqli_query($con,"insert into richtext(name,icon,content,create_time,update_time) values('$name','$url','$content',$time,$time)");
        $id=mysqli_insert_id($con);
        //生成小程序码，拿到链接后更新进对应数据
        $path="pages/my/richtext/index";
        $scene="richtext_id=$id";
        $url=getWechatQrcode($scene,$path);
        mysqli_query($con,"update richtext set url='$url' where id=$id");

        mysqli_close($con);
        if($res){
            return out_right('添加成功！');
        }else{
            return out_error('添加失败！');
        }

    }

    //编辑
    public function edit($data){
        $id=(int)$data['id'];
        $name=$data['name'];
        $content=$data['content'];
        $time=time();

        //以下是富文本src里面的base64码转化成oss文件对象地址
        ini_set('pcre.backtrack_limit', 999999999);//临时解除匹配长度限制
        preg_match_all('/\"(data:image\/[a-zA-Z]+;base64,.*?)\"/', $content, $img);
        $img=$img[1];

        for($i=0;$i<count($img);$i++){
            $file=base64_to_file::get_image($img[$i]);
            $res=oss::upload("admin/mini/".$file["name"],$file["path"]);
            $url=$res["info"]["url"];

            $content=str_replace($img[$i],$url,$content);

        }
        //以上是富文本src里面的base64码转化成oss文件对象地址
        $content = preg_replace('/<img(?![^>]*style=)/i', '<img style="width:100%;height:auto"', $content);
       // $content=str_replace("<img",'<img style="width:100%;height:auto"',$content);

        $img=$data['img'];
        $date=date('Y-m-d');
        $url='';
        for($i=0;$i<count($img);$i++){
            $file=base64_to_file::get("",$img[$i]["file_name"],$img[$i]["file"]);
            $res=oss::upload("richtext/$date/".$file["name"],$file["path"]);
            $url=$res["info"]["url"];
        }

        $con=con();
        $res=mysqli_query($con,"update richtext set name='$name',icon='$url',content='$content',update_time=$time where id=$id");
        mysqli_close($con);
        if($res){
            return out_right('修改成功！');
        }else{
            return out_error('修改失败！');
        }

    }

    //删除自定义按钮
    public function del($data){
        $id=(int)$data['id'];
        $time=time();
        $con=con();
        $res=mysqli_query($con,"update richtext set is_delete=0,delete_time=$time where id=$id");
        mysqli_close($con);
        if($res){
            return out_right('删除成功！');
        }else{
            return out_error('删除失败！');
        }
    }

    //修改状态
    public function changeStatus($request){
        $id=(int)$request['id'];
        $status=(int)$request['status'];
        $time=time();
        $con=con();
        $res=mysqli_query($con,"update richtext set status=$status,update_time=$time where id=$id");
        mysqli_close($con);
        if($res){
            return out_right();
        }else{
            return out_error();
        }
    }

    //分页列表
    public function getList($data){
        $page=(int)$data['page'];
        $size=(int)$data['size'];
        $name=$data['name'];

        $sql="select id,name,icon,url,status,is_delete,create_time,update_time,remark from richtext where is_delete=1 and status=1";
        if(!empty($name)){
            $sql.=" and `name` like '%$name%'";
        }


        $con=con();
        $data=mysqli_query($con,$sql." order by id desc limit ".($page-1)*$size.",".$size);
        $data=mysqli_fetch_all($data,true);
        $total=mysqli_query($con,$sql);
        $total=mysqli_num_rows($total);
        mysqli_close($con);
        for($i=0;$i<count($data);$i++){
            if(empty($data[$i]['url'])){
                $data[$i]['url']=[];
            }else{
                $data[$i]['url']=[$data[$i]['url']];
            }
            if(empty($data[$i]['icon'])){
                $data[$i]['icon']=[];
            }else{
                $data[$i]['icon']=[$data[$i]['icon']];
            }


        }


        return out_right([
            'data'=>$data,
            'page'=>$page,
            'size'=>$size,
            'total'=>$total,
            'total_page'=>ceil($total/$size),
        ]);
    }

    //获取二维码压缩包
    public function getZip(){
        $con=con();
        $data=mysqli_query($con,"select * from richtext where is_delete=1 and status=1");
        $data=mysqli_fetch_all($data,true);
        mysqli_close($con);
        $res=[];
        for($i=0;$i<count($data);$i++){
            if(!empty($data[$i]['url'])){
                $res[]=[
                    'name'=>$data[$i]['name'],
                    'url'=>$data[$i]['url']
                ];
            }
        }
        $url=zip::get_url($res);
        if(empty($url)){
            return out_error('获取失败！');
        }else{
            return out_right($url);
        }

    }

    //根据id查询富文本内容
    public function getContentById($data){
        $id=(int)$data['id'];
        $con=con();
        $content=mysqli_query($con,"select content from richtext where id=$id");
        $content=mysqli_fetch_all($content,true);
        mysqli_close($con);
        if(empty($content)){
            $content=null;
        }else{
            $content=$content[0]['content'];
            $content=$this->urlToBase64($content);
        }







        return out_right($content);
    }

   public function urlToBase64($content) {
        // 匹配 src="URL" 格式
        $pattern = '/src=["\'](https?:\/\/[^"\']+)["\']/i';

        return preg_replace_callback($pattern, function ($matches) {
            $url = $matches[1];

            // 获取文件内容
            $fileData = @file_get_contents($url);
            if ($fileData === false) {
                return $matches[0]; // 获取失败，返回原内容
            }

            // 获取 MIME 类型
            $mimeType = $this->getMimeType($url);
            if (!$mimeType) {
                return $matches[0]; // 获取 MIME 失败
            }

            // 转换为 Base64
            $base64 = 'data:' . $mimeType . ';base64,' . base64_encode($fileData);

            return "src=\"$base64\"";
        }, $content);
    }

// 通过 URL 获取 MIME 类型
    public function getMimeType($url) {
        $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
        $mimeTypes = [
            'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif',
            'svg' => 'image/svg+xml', 'webp' => 'image/webp', 'pdf' => 'application/pdf',
            'css' => 'text/css', 'js' => 'application/javascript',
        ];
        return $mimeTypes[strtolower($ext)] ?? null;
    }

}